/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

// dfs
class Solution {
public:
    int getAns(TreeNode* root, int tmp) {
        if (!root) return 0;
        tmp = tmp * 10 + root->val;
        if (!root->left && !root->right) return tmp;
        return getAns(root->left, tmp) + getAns(root->right, tmp);
    }
    int sumNumbers(TreeNode* root) {
        return getAns(root, 0);
    }
};

// bfs
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        if (!root) return 0;
        int sum = 0;
        // 两个队列分别存储节点和节点对应的数字
        queue<TreeNode*> nodeQueue;
        queue<int> numQueue;
        nodeQueue.push(root);
        numQueue.push(root->val);
        while (!nodeQueue.empty()) {
            TreeNode* node = nodeQueue.front();
            nodeQueue.pop();
            int num = numQueue.front();
            numQueue.pop();
            TreeNode* left = node->left;
            TreeNode* right = node->right;
            if (!left && !right) {
                sum += num;
            } else {
                if (left) {
                    nodeQueue.push(left);
                    numQueue.push(num * 10 + left->val);
                }
                if (right) {
                    nodeQueue.push(right);
                    numQueue.push(num * 10 + right->val);
                }
            }
        }
        return sum;
    }
};